/**
 * <pre>
 * Title: 		MessageServiceImpl.java
 * Project: 	itfints
 * Author:		pengfangliang
 * Create:	 	2012-7-4 上午11:24:39
 * Copyright: 	Copyright (c) 2012
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfints.service.message.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.Restrictions;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.persist.query.model.Order;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.itfinbase.en.MessagetemplatesEnum;
import com.hengpeng.itfinbase.persist.Message;
import com.hengpeng.itfinbase.persist.Message.MessageType;
import com.hengpeng.itfinbase.persist.MessageReceiver;
import com.hengpeng.itfinbase.persist.MessageTemplates;
import com.hengpeng.itfinbase.persist.MessageTemplates.BusiType;
import com.hengpeng.itfints.service.BaseService;
import com.hengpeng.itfints.service.message.MessageService;
import com.hengpeng.itfints.tools.DateTimeUtil;

/**
 * <pre>
 * 站内信服务层接口实现
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2012-7-4
 */
@Service
public class MessageServiceImpl extends BaseService implements MessageService
{
	@Override
	public List<Object> findMessageWithPage(String userName, MessageType type, Integer pageIndex, Integer pageSize,
			LinkedHashMap<String, OrderType> sort)
	{
		DynamicQuery query = new DynamicQuery(Message.class, "m").createAlias(MessageReceiver.class, "rm");
		query.eqProperty("m.id", "rm.messageId");
		query.add(Restrictions.ne("rm.isDelete", BoolValue.YES));
		query.add(Restrictions.eq("rm.userName", userName));
		query.add(Restrictions.eq("m.type", type));
		query.addProjection(Projections.property("rm.id"));
		query.addProjection(Projections.property("m.title"));
		query.addProjection(Projections.property("m.content"));
		query.addProjection(Projections.property("rm.isRead"));
		query.addProjection(Projections.property("m.publishDate"));
		query.setPageIndex(pageIndex);
		query.setPageSize(pageSize);
		query.setQueryType(QueryType.JDBC);
		if (sort != null)
		{
			for (Entry<String, OrderType> iterable_element : sort.entrySet())
			{
				if (iterable_element.getValue() == Order.OrderType.ASC)
				{
					query.asc(iterable_element.getKey());
				}
				else
				{
					query.desc(iterable_element.getKey());
				}
			}
		}
		return serviceFactory.getPersistService().findObject(null, query);
	}

	@Override
	public Long findMessageWithCount(String userName, MessageType type)
	{
		DynamicQuery query = new DynamicQuery(Message.class, "m").createAlias(MessageReceiver.class, "rm");
		query.eqProperty("m.id", "rm.messageId");
		query.add(Restrictions.ne("rm.isDelete", BoolValue.YES));
		query.add(Restrictions.eq("rm.userName", userName));
		query.add(Restrictions.eq("m.type", type));
		query.addProjection(Projections.count());
		return serviceFactory.getPersistService().count(query);
	}

	@Override
    public ServiceResult<List<Message>>  findMesWithPage(String userName, MessageType type, Integer pageIndex, Integer pageSize,
            LinkedHashMap<String, OrderType> sort)
    {
        DynamicQuery query = new DynamicQuery(Message.class, "m");
        query.add(Restrictions.eq("m.userName", userName));
        query.add(Restrictions.eq("m.type", type));
        query.setPageIndex(pageIndex);
        query.setPageSize(pageSize);
        query.setQueryType(QueryType.JDBC);
        if (sort != null)
        {
            for (Entry<String, OrderType> iterable_element : sort.entrySet())
            {
                if (iterable_element.getValue() == Order.OrderType.ASC)
                {
                    query.asc(iterable_element.getKey());
                }
                else
                {
                    query.desc(iterable_element.getKey());
                }
            }
        }
        ServiceResult<List<Message>> serviceResult = new ServiceResult<List<Message>>();
        QueryResult<Message> result =  serviceFactory.getPersistService().findWithPage(Message.class, query);
        Long count = result.getTotalCount();
        serviceResult.setReturnValue(result.getResults());
        serviceResult.setReturnListSize((int) (this.findMessCount(userName, type)==null?1:this.findMessCount(userName, type)));
        serviceResult.setIsSuccess(result.getIsSuccess());
        return serviceResult;
    }
	
	@Override
    public Long findMessCount(String userName, MessageType type)
    {
	    DynamicQuery query = new DynamicQuery(Message.class, "m");
        query.add(Restrictions.eq("m.userName", userName));
        query.add(Restrictions.eq("m.type", type));
        query.addProjection(Projections.count());
        return serviceFactory.getPersistService().count(query);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void sendSystemMessage(String userName, String title, String content)
    {
        Message message = new Message();
        message.setUserName(userName);
        message.setContent(content);
        message.setCreatDate(new Date());
        message.setIsPublish(BoolValue.YES);
        message.setPublishDate(new Date());
        message.setReadRate(0);
        message.setReadTotal(0);
        message.setReceiverTotal(1);
        message.setSender(MessageType.COMMON.toString());
        message.setSummary(null);
        message.setTitle(title);
        message.setType(MessageType.COMMON);// 系统发送
        message = serviceFactory.getPersistService().save(message);
    }
    
    @Override
    public String sendSystemMessageByType(String userName, String busiType,Map<String,?> map)
    {
        MessageTemplates messageTemplates = this.getMessageTemplatesByType(busiType, 1);
        if(null == messageTemplates || StringUtils.isEmpty(messageTemplates.getContent())){
            return null;
        }
        String messageTemplatesContent = messageTemplates.getContent();
        String content = messageTemplatesContent.replaceAll(MessagetemplatesEnum.DATE.getText(),map.get("date")==null?"":DateTimeUtil.formatLongStr((Date) map.get("date"))).
                replaceAll(MessagetemplatesEnum.MONEY.getText(),map.get("money")==null?"":map.get("money").toString())
                .replace(MessagetemplatesEnum.USERNAME.getText(), map.get("userName")==null?"":map.get("userName").toString());
        this.sendSystemMessage(userName, "", content);
        return content;
    }
    
    
    
    private MessageTemplates getMessageTemplatesByType(String busiType,Integer status){
        
        DynamicQuery query = new DynamicQuery(MessageTemplates.class);
        if(!StringUtils.isEmpty(busiType)){
            BusiType b = BusiType.getBusiTypeByName(busiType);
            query.eq("busitype", b);
        }
        if(null != status){
            query.eq("status", status);
        }
        query.setQueryType(QueryType.JDBC);
       return this.serviceFactory.getPersistService().getEntity(query,MessageTemplates.class);
    }
}
